<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import HeaderNav from '../../components/layout/HeaderNav.vue'
import AdminHeaderNav from '../../components/layout/AdminHeaderNav.vue'
import CartHeader from '../../components/cart/CartHeader.vue'
import CartActionBar from '../../components/cart/CartActionBar.vue'
import StoreGroup from '../../components/cart/StoreGroup.vue'
import CartSideDock from '../../components/cart/CartSideDock.vue'
import { useUserStore } from '../../stores/user'
import { deleteCart, getCartList, updateBuyCount, getCartTotalCount, getCartByName } from '../../api/cart'
import router from '../../router/index.ts'

const userStore = useUserStore()

// 根据用户类型决定显示哪个导航栏
const isAdmin = computed(() => userStore.isAdmin)

// 定义购物车数据类型，与CartItem组件接口一致
interface CartItemData {
  // CartItem组件期望的字段
  id: string
  itemId: string
  title: string
  image: string
  price: number
  num: number
  checked: boolean
  spec: string | Record<string, string>
  // 可选字段
  returnPolicy?: string
  discountInfo?: string
  paymentInfo?: string
  // 后端原始数据（保留用于API调用）
  userId?: number
  status?: number
  createTime?: string
  updateTime?: string
  storeId?: string
  storeName?: string
}

interface StoreData {
  id: string
  name: string
  type: string
  checked: boolean
  items: CartItemData[]
}

interface CartDataType {
  stores: StoreData[]
}



// 购物车数据
const cartData = ref<CartDataType>({
  stores: []
})

// 加载状态
const loading = ref(false)

// 购物车商品总数
const cartTotalCount = ref(0)

// 搜索状态
const isSearching = ref(false)
const searchKeyword = ref('')

// 获取购物车数据的函数
const fetchCartData = async () => {
  loading.value = true
  // 重置搜索状态
  isSearching.value = false
  searchKeyword.value = ''
  try {
    const res = await getCartList() as any
    console.log('购物车API返回数据:', res)
    
    // 检查返回的数据结构 - res直接就是后端的Result对象
    if (res?.code === 0) {
      // 成功获取数据
      const cartItems = res.data || []
      console.log('购物车商品列表:', cartItems)
      
      if (Array.isArray(cartItems) && cartItems.length > 0) {
        // 将所有商品放到一个默认店铺中
        cartData.value = {
          stores: [
            {
              id: '1',
              name: '宝可得店铺',
              type: '官方店',
              checked: true,
              items: cartItems.map((item: any) => ({
                // CartItem组件期望的字段
                id: String(item.id), // 转为字符串类型
                itemId: String(item.itemId),
                title: item.name || '', // 后端返回name，前端组件期望title
                image: item.image || '',
                price: Number(item.isKill === 1 ? item.killPrice : item.price) || 0,
                originalPrice: item.isKill === 1 ? Number(item.price) : undefined,
                isKill: item.isKill === 1,
                num: Number(item.num),
                checked: true, // 默认选中
                spec: item.spec || '',
                // 可选字段
                returnPolicy: '7天无理由退货',
                discountInfo: '',
                paymentInfo: '',
                // 后端原始数据（保留用于API调用）
                userId: Number(item.userId),
                status: Number(item.status) || 0,
                createTime: item.createTime || '',
                updateTime: item.updateTime || '',
                storeId: '1',
                storeName: '宝可得店铺'
              }))
            }
          ]
        }
      } else {
        // 空购物车
        cartData.value = { stores: [] }
      }
      
      // 获取购物车总数和总价
      await fetchCartTotals()
    } else {
      // 不显示错误提示，由拦截器统一处理
      cartData.value = { stores: [] }
    }
  } catch (error) {
    console.error('获取购物车数据异常:', error)
    // 401错误已在请求拦截器中处理并显示提示，这里不再重复显示错误
    cartData.value = { stores: [] }
  } finally {
    loading.value = false
  }
}

// 获取购物车总数的函数
const fetchCartTotals = async () => {
  try {
    // 获取购物车总数
    const countRes = await getCartTotalCount() as any
    console.log('购物车总数API返回:', countRes)
    
    if (countRes?.code === 0) {
      cartTotalCount.value = Number(countRes.data) || 0
    }
    
    // 总价由前端的 selectedTotalPrice 计算属性直接计算，不需要调用API
  } catch (error) {
    console.error('获取购物车总数异常:', error)
    // 这里不显示错误信息，因为即使获取失败，前端也可以计算
  }
}

const allChecked = computed(() => {
  return cartData.value.stores.length > 0 && cartData.value.stores.every(store => store.checked)
})

const selectedCount = computed(() => {
  return cartData.value.stores.reduce((total, store) => {
    return total + store.items.filter(item => item.checked).reduce((sum, item) => sum + item.num, 0)
  }, 0)
})

// 计算选中商品的总价
const selectedTotalPrice = computed(() => {
  return cartData.value.stores.reduce((total, store) => {
    return total + store.items.filter(item => item.checked).reduce((sum, item) => sum + (item.price * item.num), 0)
  }, 0)
})

const selectedItems = computed(() => {
  const items: any[] = []
  cartData.value.stores.forEach(store => {
    store.items.forEach(item => {
      if (item.checked) {
        items.push(item)
      }
    })
  })
  return items
})

const hasItems = computed(() => {
  return cartData.value.stores.length > 0 && cartData.value.stores.some(store => store.items.length > 0)
})

// 方法
const handleStoreCheckChange = (storeId: string, checked: boolean) => {
  const store = cartData.value.stores.find(s => s.id === storeId)
  if (store) {
    store.checked = checked
    store.items.forEach(item => {
      item.checked = checked
    })
  }
}

const handleItemCheckChange = (itemId: string, checked: boolean) => {
  cartData.value.stores.forEach(store => {
    const item = store.items.find(i => i.id === itemId)
    if (item) {
      item.checked = checked
      // 更新店铺选中状态
      store.checked = store.items.every(i => i.checked)
    }
  })
}

// 处理数量变化
const handleQuantityChange = async (itemId: string, num: number) => {
  try {
    const res = await updateBuyCount(Number(itemId), num) as any
    console.log('更新数量API返回:', res)
    
    if (res?.code === 0) {
      // 成功更新
      const item = cartData.value.stores.find(store => store.items.some(i => i.id === itemId))?.items.find(i => i.id === itemId)
      if (item) {
        item.num = num
      }
      ElMessage.success('数量更新成功')
    } else {
      // 不显示错误提示，由拦截器统一处理
    }
    
    // 更新购物车总数和总价
    await fetchCartTotals()
  } catch (error) {
    console.error('更新购物车商品数量异常:', error)
    // 不显示错误提示，由拦截器统一处理
    // 发生异常时，重新获取购物车数据
    await fetchCartData()
  }
}

const handleMoveToFavorite = (_itemId: string) => {
  ElMessage.success('已移入收藏夹')
}

// 删除购物车商品
const handleDeleteItem = async (itemId: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 用户点击确定，执行删除
    const res = await deleteCart(Number(itemId)) as any
    console.log('删除商品API返回:', res)
    
    if (res?.code === 0) {
      // 成功删除
      cartData.value.stores.forEach(store => {
        store.items = store.items.filter(item => item.id !== itemId)
      })
      // 删除空的店铺
      cartData.value.stores = cartData.value.stores.filter(store => store.items.length > 0)
      ElMessage.success('商品删除成功')
      // 重新获取购物车数据以保持数据一致性
      await fetchCartData()
    } else {
      // 不显示错误提示，由拦截器统一处理
    }
  } catch (error) {
    // 判断是用户取消还是真正的异常
    if (error === 'cancel') {
      // 用户点击取消
      ElMessage.info('取消删除购物车')
      return
    }
    // 真正的异常
    console.error('删除购物车商品异常:', error)
    // 不显示错误提示，由拦截器统一处理
    // 发生异常时，重新获取购物车数据
    await fetchCartData()
  }
}

// 切换全选
const handleToggleAll = (checked: boolean) => {
  cartData.value.stores.forEach(store => {
    store.checked = checked
    store.items.forEach(item => {
      item.checked = checked
    })
  })
}

// 全选移入收藏夹
const handleMoveToFavoriteAll = () => {
  const selectedItems = cartData.value.stores
    .filter(store => store.checked)
    .flatMap(store => store.items.filter(item => item.checked))
  
  if (selectedItems.length === 0) {
    ElMessage.warning('请先选择要移入收藏夹的商品')
    return
  }
  
  ElMessage.success(`已将${selectedItems.length}个商品移入收藏夹`)
}

const handleDeleteSelected = async () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择要删除的商品')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的${selectedItems.value.length}个商品吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const results = await Promise.allSettled(
      selectedItems.value.map(item => deleteCart(Number(item.id)))
    )
    
    let successCount = 0
    let failCount = 0
    
    results.forEach((result, index) => {
      if (result.status === 'fulfilled' && (result.value as any)?.code === 0) {
        successCount++
      } else {
        failCount++
        console.error(`删除商品${selectedItems.value[index].id}失败:`, result)
      }
    })
    
    if (successCount > 0 && failCount === 0) {
      ElMessage.success(`成功删除${successCount}个商品`)
    } else if (successCount > 0 && failCount > 0) {
      ElMessage.warning(`成功删除${successCount}个商品，${failCount}个商品删除失败`)
    } else {
      // 不显示错误提示，由拦截器统一处理
    }
    
    // 删除后刷新购物车数据
    await fetchCartData()
  } catch (error) {
    // 判断是用户取消还是真正的异常
    if (error === 'cancel') {
      // 用户点击取消
      ElMessage.info('取消删除购物车')
      return
    }
    // 真正的异常
    console.error('批量删除购物车商品异常:', error)
    // 不显示错误提示，由拦截器统一处理
    await fetchCartData()
  }
}

const handleSearch = async (keyword: string) => {
  console.log('搜索关键词:', keyword)
  
  if (!keyword.trim()) {
    // 空关键词，重新加载所有数据
    await fetchCartData()
    return
  }
  
  try {
    loading.value = true
    // 设置搜索状态
    isSearching.value = true
    searchKeyword.value = keyword
    
    const res = await getCartByName(keyword) as any
    console.log('搜索API返回:', res)
    
    if (res?.code === 0) {
      const searchResults = res.data || []
      console.log('搜索结果:', searchResults)
      
      if (Array.isArray(searchResults) && searchResults.length > 0) {
        // 将搜索结果转换为显示格式
        cartData.value = {
          stores: [
            {
              id: '1',
              name: '宝可得店铺',
              type: '官方店',
              checked: true,
              items: searchResults.map((item: any) => ({
                id: String(item.id),
                itemId: String(item.itemId),
                title: item.name || '',
                image: item.image || '',
                price: Number(item.isKill === 1 ? item.killPrice : item.price) || 0,
                originalPrice: item.isKill === 1 ? Number(item.price) : undefined,
                isKill: item.isKill === 1,
                num: Number(item.num),
                checked: true,
                spec: item.spec || '',
                returnPolicy: '7天无理由退货',
                discountInfo: '',
                paymentInfo: '',
                userId: Number(item.userId),
                status: Number(item.status) || 0,
                createTime: item.createTime || '',
                updateTime: item.updateTime || '',
                storeId: '1',
                storeName: '宝可得店铺'
              }))
            }
          ]
        }
        ElMessage.success(`找到 ${searchResults.length} 个相关商品`)
      } else {
        // 没有搜索结果，但保持搜索状态
        cartData.value = { stores: [] }
        ElMessage.info('没有找到相关商品')
      }
    } else {
      // 不显示错误提示，由拦截器统一处理
      cartData.value = { stores: [] }
    }
  } catch (error) {
    console.error('搜索异常:', error)
    // 不显示错误提示，由拦截器统一处理
    cartData.value = { stores: [] }
  } finally {
    loading.value = false
  }
}

// 结算处理函数
const handleCheckout = async () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }

  try {
    // 创建订单
    const orderItems = selectedItems.value.map(item => {
      const store = cartData.value.stores.find(s => s.items.some(i => i.id === item.id))
      return {
        id: item.id,
        itemId: item.itemId,
        title: item.title,
        image: item.image,
        price: item.price,
        num: item.num, // 使用 num 而不是 quantity
        spec: item.spec,
        storeId: store?.id || '',
        storeName: store?.name || ''
      }
    })
    
    // 将商品数据序列化并编码，传递到订单确认页面
    const serializedItems = encodeURIComponent(JSON.stringify(orderItems))
    console.log('订单数据：', orderItems);
    
    // 跳转到订单确认页面
    router.push({
      path: '/cart/order-confirm',
      query: {
        items: serializedItems
      }
    })
  } catch (error) {
    console.error('跳转订单确认页面失败:', error)
    // 不显示错误提示，由拦截器统一处理
  } finally {
    loading.value = false
  }
}

const goShopping = () => {
  // ElMessage.info('即将跳转到商品列表页面')
  //跳转到主页面
  router.push('/layout')
 
}

// 监听购物车数据变化
// watch(cartData, (newData) => {
//   // console.log('购物车数据更新:', newData)
// }, { deep: true })

onMounted(() => {
  // 页面加载时获取购物车数据
  fetchCartData()
})
</script>

<template>
  <div class="page-wrap">
    <!-- 根据用户类型显示不同的导航栏 -->
    <AdminHeaderNav v-if="isAdmin" />
    <HeaderNav v-else />
    <div class="cart-content">
      <CartHeader />
      
      <div class="cart-main">
        <!-- 加载中状态 -->
        <div v-if="loading" class="loading-cart">
          <el-loading-spinner size="large" />
          <p>正在加载购物车数据...</p>
        </div>
        
        <!-- 空购物车状态 -->
        <div v-else-if="!hasItems" class="empty-cart">
          <!-- 搜索无结果状态 -->
          <template v-if="isSearching">
            <div class="empty-icon">
              <el-icon size="80" color="#ff6a00">
                <Search />
              </el-icon>
            </div>
            <div class="empty-text">没有找到"{{ searchKeyword }}"相关的商品</div>
            <div class="empty-tip">试试其他关键词或清空搜索查看所有商品</div>
            <button class="go-shopping-btn" @click="fetchCartData">
              查看所有商品
            </button>
          </template>
          <!-- 购物车真正为空的状态 -->
          <template v-else>
            <div class="empty-icon">
              <svg width="100" height="100" viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg">
                <!-- 购物袋主体 -->
                <path d="M20 25h40l-5 30H25L20 25z" fill="#ff6a00" stroke="#ff6a00" stroke-width="2"/>
                <!-- 购物袋内部 -->
                <path d="M22 27h36l-4 26H26L22 27z" fill="#ff8c00"/>
                <!-- 购物袋手柄 -->
                <path d="M25 25c0-2.76 2.24-5 5-5h20c2.76 0 5 2.24 5 5" stroke="#ff6a00" stroke-width="2" fill="none"/>
                <!-- VIP标签 -->
                <rect x="28" y="20" width="8" height="12" fill="#ff6a00" rx="1"/>
                <text x="32" y="28" fill="white" font-size="6" text-anchor="middle" transform="rotate(90 32 28)">VIP</text>
                <!-- 发光效果 -->
                <path d="M40 15l-2 5M40 15l2 5M40 15l0 5" stroke="#ffcc80" stroke-width="1" opacity="0.6"/>
              </svg>
            </div>
            <div class="empty-text">你的购物车还没有商品</div>
            <div class="empty-tip">再去逛逛吧~</div>
            <button class="go-shopping-btn" @click="goShopping">
              去购物
            </button>
          </template>
        </div>
        
        <!-- 有商品时显示购物车内容 -->
        <template v-else>
          <CartActionBar
            :all-checked="allChecked"
            :selected-count="selectedCount"
            :total-count="cartTotalCount"
            @toggle-all="handleToggleAll"
            @move-favorite="handleMoveToFavoriteAll"
            @delete-selected="handleDeleteSelected"
            @search="handleSearch"
          />
          
          <div class="stores-list">
            <StoreGroup
              v-for="store in cartData.stores"
              :key="store.id"
              :store="store"
              :loading="loading"
              @store-check-change="handleStoreCheckChange"
              @item-check-change="handleItemCheckChange"
              @item-quantity-change="handleQuantityChange"
              @item-move-favorite="handleMoveToFavorite"
              @item-delete="handleDeleteItem"
            />
          </div>
        </template>
      </div>
      
      <!-- 右侧浮动购物袋与抽屉 -->
      <CartSideDock
        v-if="hasItems"
        :items="selectedItems"
        :total="selectedTotalPrice"
        :total-count="selectedCount"
        :loading="loading"
        @checkout="handleCheckout"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.page-wrap {
  padding: 0 2.5rem; // 与主页面 Layout.vue 保持一致
}

.cart-content {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  padding: 0.5rem 0;
  max-width: 75rem;
  margin: 0 auto;
  width: 100%;
}

.cart-main {
  flex: 1;
  min-width: 0; // 防止flex子项溢出
  border-radius: 0.5rem;
  overflow: hidden;
}

.empty-cart {
        padding: 4rem 2rem;
        text-align: center;
        background: #fff;
        border-radius: 0.5rem;
        box-shadow: 0 0.0625rem 0.1875rem rgba(0,0,0,0.1);
      }
      
      .empty-cart .empty-icon {
        margin-bottom: 1.5rem;
        display: flex;
        justify-content: center;
      }
      
      .empty-cart .empty-icon svg {
        filter: drop-shadow(0 0.25rem 0.5rem rgba(255, 106, 0, 0.2));
      }
      
      .empty-cart .empty-text {
        font-size: 1.25rem;
        color: #333;
        margin-bottom: 0.5rem;
        font-weight: 500;
      }
      
      .empty-cart .empty-tip {
        font-size: 1rem;
        color: #666;
        margin-bottom: 2rem;
      }
      
      .empty-cart .go-shopping-btn {
        background: linear-gradient(135deg, #ff6a00, #ff8c00);
        color: white;
        border: none;
        padding: 0.75rem 1.5rem;
        border-radius: 2rem;
        font-size: 1rem;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 0.25rem 0.75rem rgba(255, 106, 0, 0.3);
      }
      
      .empty-cart .go-shopping-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 0.5rem 1rem rgba(255, 106, 0, 0.4);
      }
      
      .empty-cart .go-shopping-btn:active {
        transform: translateY(0);
      }

      .loading-cart {
        padding: 8rem 2rem;
        text-align: center;
        background: #fff;
        border-radius: 0.5rem;
        box-shadow: 0 0.0625rem 0.1875rem rgba(0,0,0,0.1);
        
        .el-loading-spinner {
          margin-bottom: 1.5rem;
          display: inline-block;
        }
        
        p {
          font-size: 1rem;
          color: #666;
        }
      }

.stores-list {
  margin-bottom: 4rem; // 为底部固定结算栏留出空间
  border-radius: 0.5rem;
  overflow: hidden;
  box-shadow: 0 0.0625rem 0.1875rem rgba(0,0,0,0.1);
  
  .store-group:last-child {
    margin-bottom: 0;
  }
}

.cart-sidebar {
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
  
  .cart-summary {
    max-width: 75rem;
    margin: 0 auto;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  }
}

/* 响应式设计 */
@media (max-width: 64rem) {
  .cart-content {
    max-width: 100%;
  }
  
  .cart-sidebar .cart-summary {
    max-width: 100%;
  }
}

@media (max-width: 48rem) {
  .cart-content {
    padding: 0.25rem 0;
  }
  
  .stores-list {
    margin-bottom: 6rem; // 移动端底部结算栏更高
  }
  
  .empty-cart {
    padding: 3rem 1rem;
    
    .empty-icon svg {
      width: 60px;
      height: 60px;
    }
    
    .empty-text {
      font-size: 1.125rem;
    }
    
    .empty-tip {
      font-size: 0.9375rem;
    }
    
    .go-shopping-btn {
      padding: 0.625rem 1.5rem;
      font-size: 0.9375rem;
    }
  }
}
</style>


